<?php

namespace Btr\DurakBundle\Durak;
 
class ComputerPlayer extends Player
{
	public function __construct(array $array = null)
	{
		parent::__construct($array);
	}
	
	/**
	 * (non-PHPdoc)
	 * @see \Btr\DurakBundle\Durak\Player::getAttackCard()
	 */
	public function getAttackCard(Durak $game)
	{
		// We need more cards.
		if ( parent::getAttackCard($game) === 0 ) return 0;
		
		// master suit
		$masterSuit = $game->getCards()->getMasterSuit() & 0xF0;
		$cardsAttackable = $this->getCardsAttackable($game);
		// No card can attack, stop attack		
		if ( count($cardsAttackable) == 0 )
		{
			return -1;			
		}	

		$cardsAvailableBySuit = $this->getCardsAttackableBySuit();
		
		// Get master cards.
		$masterCards = array();
		if ( array_key_exists($masterSuit, $cardsAvailableBySuit))
		{
			$masterCards = $cardsAvailableBySuit[$masterSuit];
			sort($masterCards);
			unset($cardsAvailableBySuit[$masterSuit]);
		}
		
		// Try non-master-suit card first
		if ( count($cardsAvailableBySuit) > 0 )
		{
			foreach ( $cardsAvailableBySuit as $suit => $cards)
			{
				// Choose minimum card.
				sort($cards);
				$card = $suit + $cards[0];
				break;
			}
		}
		else 
		{
			// All master cards
			// no more card left or first attack , have to attack by master suit card.
			$numOfCardsAttackable = count($game->getCards());
			if ( count($game->getRounds()) == 0 || $numOfCardsAttackable <= 2 )
			{
					sort($masterCards);
					$card = $masterSuit + $masterCards[0];
			}
			else
			{
				// we can stop attack.
				return -1;
			}
		}
	
		// remove card.
		$index = array_search($card, $this->cards);
		unset($this->cards[$index]);
		return $card;
	}
	
	/**
	 * (non-PHPdoc)
	 * @see \Btr\DurakBundle\Durak\Player::getDefendCard()
	 */
	public function getDefendCard(Durak $game, $attackCard)
	{
		$cardsDefendable = $this->getCardsDefendable($game, $attackCard);
		// Can not defend, have to accept the cards.
		if ( count($cardsDefendable)==0) return -1;
		$masterSuit = $game->getCards()->getMasterSuit() & 0xF0;
		$cardsDefendableBySuit = $this->getCardsDefendableBySuit();
		
		// First, check non-master-suit card.
		$card = -1;
		$attackSuit = $attackCard & 0xF0;
		$attackValue = $attackCard & 0x0F;
		if (array_key_exists($attackSuit, $cardsDefendableBySuit))
		{
			$cards = $cardsDefendableBySuit[$attackSuit];
			sort($cards);
			$card = $attackSuit + $cards[0];
		}
		elseif ( $attackSuit != $masterSuit )
		{ 	// Choose master suit card
			if (array_key_exists($masterSuit, $cardsDefendableBySuit))
			{
				$cards = $cardsDefendableBySuit[$masterSuit];
				sort($cards);
				$card = $masterSuit + $cards[0];
			}
		}
		
		if ( -1 != $card)
		{	// remove card.
			$index = array_search($card, $this->cards);
			unset($this->cards[$index]);
		}
		return $card;		
	}
	
	/**
	 * Check it can accept cards automatially.
	 * @return boolean
	 */
	public function isAutoAccept()
	{
		return true;
	}
	
	
} 